package com.jianggy.kerberos;


import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.security.UserGroupInformation;

import java.sql.*;

/**
 *jdbc通过kerberos认证连接hive
 *@author jianggy
 *@date 2022/12/26
 *@version 1.0
 **/
public class HiveTest {
    private static String JDBC_DRIVER = "org.apache.hive.jdbc.HiveDriver";
    private static String CONNECTION_URL = "jdbc:hive2://hadoop2:10000/default;principal=hive/hadoop2@INSIGHTONE.CN";

    public static void main(String[] args) throws SQLException {
        Connection connection  = null;
        try {
            Class.forName(JDBC_DRIVER);
            System.setProperty("java.security.krb5.conf", "C:\\ProgramData\\MIT\\Kerberos5\\krb5.ini");
            // System.setProperty("java.security.krb5.conf", "/etc/krb5.conf");
            Configuration configuration = new Configuration();
            configuration.set("hadoop.security.authentication", "Kerberos");
            configuration.setBoolean("hadoop.security.authorization", true);
            UserGroupInformation.setConfiguration(configuration);
            UserGroupInformation.loginUserFromKeytab("hive/admin@INSIGHTONE.CN", "C:\\keytab\\hive-user.keytab");
            // UserGroupInformation.loginUserFromKeytab("hive/admin@INSIGHTONE.CN", "/etc/security/keytabs/hive-user.keytab");
            Class.forName(JDBC_DRIVER);
            connection = DriverManager.getConnection(CONNECTION_URL);
            Statement statement = connection.createStatement();
            String sql = "select * from test";
            ResultSet resultSet = statement.executeQuery(sql);
            while (resultSet.next()){
                System.out.println(resultSet.getString(1)+"--"+resultSet.getString(2));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (connection!=null){
                connection.close();
            }
        }

    }
}
